package com.gray.wow.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.gray.wow.biz.TagBiz;
import com.gray.wow.common.*;
import com.gray.wow.domain.PageModel;
import com.gray.wow.domain.Tag;
import com.gray.wow.domain.User;

@Controller
@RequestMapping("/tag")
public class TagController {

	@Resource
	private TagBiz tagBiz;

	// 标签管理
	@RequestMapping(value = "/manage", method = RequestMethod.GET)
	public String tag(HttpServletRequest request) {
		User admin = (User) request.getSession().getAttribute("admin");
		if (admin != null) {
			PageModel pageModel=tagBiz.getTag(Page.PAGE_DEFAULT, Page.PAGESIZE_ALL);
			request.setAttribute("pageModel", pageModel);
			return "admin/tag/tag";
		}
		return null;
	}

	@RequestMapping("/add")
	public String add(Integer id, HttpServletRequest request) {
		User admin = (User) request.getSession().getAttribute("admin");
		if (admin != null) {
			return "admin/tag/saveTag";
		}
		return null;
	}

	@RequestMapping("/edit")
	public String edit(Integer id, HttpServletRequest request) {
		User admin = (User) request.getSession().getAttribute("admin");
		if (admin != null) {
			Tag tag = tagBiz.getTagById(id);
			if (tag != null) {
				request.setAttribute("tag", tag);
			}

			return "admin/tag/saveTag";
		}
		return null;
	}

	@RequestMapping("/save")
	public String save(HttpServletRequest request,
			HttpServletResponse response, Tag tag) {
		try {
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			if(tagBiz.saveTag(tag))
			out.print("success");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "admin/tag/tag";
	}

	@RequestMapping("/delete")
	public String delete(int[] ids, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setContentType("text/html; charset=UTF-8");
			PrintWriter out = response.getWriter();
			User admin = (User) request.getSession().getAttribute("admin");
			if (admin != null) {
				if(tagBiz.delTag(ids))
				out.print("success");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
